///<reference path="../../service/weixin.d.ts"/>
import {Component} from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
// import { CommonModule } from '@angular/common';

import {GetVideoDetailService} from "../../service/http-service/getVideoDetail.service";
import {ApplicantService} from "../../service/http-service/applicant.service";
import { CommonHttpService } from '../../service/http-service/common/common-http-service';
// import {MystatePage} from "../mystate/mystate";
import {PostwatchednumService} from "../../service/http-service/postwatchednum.service";
import {ValidateUtils} from "../../util/validate-utils";

// import {VgAPI} from "videogular2/core";
// import {PhonePage} from "../phone/phone";


/**
 * Generated class for the ListvidoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

 @IonicPage(
   {
     name: 'ListvidoPage',
     segment: 'listvido/:Id'
   }

  )
@Component({
  selector: 'page-listvido',
  templateUrl: 'listvido.html',

})
export class ListvidoPage {

  video = {"img": "", "name": "", "type": "", "depict": "", "id": "", "url": "", "average_score": "","access_flag":""};
  // video={"id": "", "userid": "", "username": "", "commidityId": "","comment":""};
  comment_list: Array<{ id: string, userid: string, username: string, commidityId: string, comment: string, ifThumbsUp: boolean, gmtCreate: number }>;
  videoID: string;
  comment = {"size": ""};
  toastCtrl: ToastController;
  paySign: boolean;
  src: any;
  v: any;
  url: any;
  // width: number;

  // isPlaying : any;
  average_score: any;
  // videoUrl: any;
  currentPage: any;
  lastPage: any;
  scrollSign: any;
  timeStampWc: string;
  appIdWc: string;
  nonceStrWc: string;
  signatureWc: string;



  sources: Array<Object>;

  // api:VgAPI;
  constructor(public iab: InAppBrowser, public valite: ValidateUtils, public postwatchednum:
    PostwatchednumService, public navCtrl: NavController, public navParams: NavParams,
              public getVideoDetailservice: GetVideoDetailService, public  applicationService: ApplicantService,
              public toastService: ToastController, public commonHttp: CommonHttpService)
  {
    this.videoID = navParams.get("Id");
    // this.videoUrl = navParams.get("Url")
    // console.log("dddddddddddddd");
    console.log(this.videoID);
    // console.log(this.videoUrl);

    this.toastCtrl = toastService;





  }

  applePlay() {

    this.iab.create(this.video.url, '_self', {location: "yes"});


  }

  /*
      +  * 上传视频观看次数
      +  * */
  postWatchedNum() {
    this.postwatchednum.postWatchedNum(this.videoID).subscribe(resp => {
      if (resp.data !== null && resp.code == 200) {
        console.log("观看视频次数：" + resp.data);
      }
    }, error2 => {


      console.log(error2);
    })
  }

  /**
   * 获取视频详情
   */
  getVideoDetail() {
    this.getVideoDetailservice.getVideoDetail(this.videoID).subscribe(resp => {
      if (resp.data !== null && resp.code == 200) {
        this.video = resp.data;


        this.average_score = Math.floor(resp.data.average_score * 10 + 0.5) / 10;
        // console.log(resp.data);
        // localStorage.setItem("video111", resp.data);
        // console.log(this.video.url)
        // if(this.video.access_flag =="1"){
        //   this.paySign = false;
        // }else{
        //   this.paySign = true;
        //
        // }
        console.log("this.video.access_flag")
        // console.log(this.paySign);

        // console.log(rr);
        // if (rr==null) {
        //   var v = document.getElementsByTagName("video")[0];
        //
        //   v.src = this.video.url;
        //   v.addEventListener("seemed", function () {
        //     v.play();
        //   }, false);
        // }
        this.androidVideo();
        this.postWatchedNum();
      } else if (resp.data !== null && resp.code == 1401) {
        console.log("errrovideo");
        this.applicationService.freshTokenn();
      }
    }, error2 => {

      console.log(error2);
    });
  }

  /**
   * 视频播放封装
   */
  androidVideo() {


      var v = document.getElementsByTagName("video")[0];
      console.log(v);
      if(v) {

        v.src = this.video.url;
        v.addEventListener("seeked", function () {
          v.play();
        }, false);

      }
  }

  /**
   * 获取视频评论列表
   */
  getComments() {
    this.getVideoDetailservice.getVideoCommend(this.videoID, '1').subscribe(resp => {
      if (resp.data !== null && resp.code == 200) {
        console.log(resp.data);
        this.comment_list = resp.data.list;
        this.currentPage = 1;
        this.lastPage = resp.data.isLastPage;
        // for (var i=0;i<this.comment_list.length;i++){
        //   var commentTime=new Date(this.comment_list[i].gmtCreate).toLocaleString().replace(/年|月/g,"-").replace(/日/g," ");
        //   console.log("commentTime="+commentTime);
        //   this.comment_list1[i].gmtCreate=commentTime;
        //   this.comment_list1[i].userid=this.comment_list[i].userid;
        //   this.comment_list1[i].id=this.comment_list[i].id;
        //   this.comment_list1[i].comment=this.comment_list[i].comment;
        //   this.comment_list1[i].username=this.comment_list[i].username;
        //   this.comment_list1[i].commidityId=this.comment_list[i].commidityId;
        //   this.comment_list1[i].ifThumbsUp=this.comment_list[i].ifThumbsUp;
        // }
        this.comment = resp.data;
      } else if (resp.data !== null && resp.code == 1401) {
        this.applicationService.freshTokenn();
      }
      console.log("comment_list:", this.comment_list);
    }, error2 => {
      console.log("error21");
    });
  }

  //格式化评论日期
  date1(time: any) {
    return new Date(time).toLocaleString().replace(/:\d{1,2}$/, ' ');
  }


  ionViewWillEnter() {
    console.log('ionViewDidLoad ListvidoPage');
    this.getVideoDetail();
    this.getComments();
    // this.setStar();
    // history.pushState(null,null,"listvido/pay")


  }

  // ionViewDidLoad() {
  //   console.log('ionViewDidLoad ListvidoPage');
  //   this.getVideoDetail();
  //   this.getComments();
  // }
  buySingle() {
    this.navCtrl.push('PayPage',{'Id':this.videoID});
  }

  buyVip() {
    this.navCtrl.push('VipPage');
  }

  /**
   视频简介折叠
   */

  open_intro() {
    var btn = document.querySelector('#dic_c');//className 为要获取元素的class

    if ("intro" == btn.className.toString()) {
      btn.className = "intro2";
    } else {
      btn.className = "intro";
    }
  }

  /**
   * 视频评论点赞
   * @param {string} commendId
   * @param {boolean} ifthumbup
   */
  goThumb(commendId: string, ifthumbup: boolean) {
    if (!ifthumbup) {
      this.getVideoDetailservice.getThumbCommend(commendId).subscribe(resp => {
        if (resp.data !== null && resp.code == 200) {
          console.log(resp.data);
          // let thumbNum=document.getElementById("myDiv");
          // thumbNum.querySelector('thumb_num').innerHTML='hjh';
        } else if (resp.data !== null && resp.code == 1401) {
          this.applicationService.freshTokenn();
        }
      }, error2 => {
        console.log("error22");
      });
    } else {
      alert("您已点过赞，不能重复点赞哦")
    }
  }

  ifComment() {
    var v = document.getElementsByTagName("video")[0];
    if(v) {
      v.pause();
    }
    this.getVideoDetailservice.ifCommend(this.videoID).subscribe(resp => {

      if (resp.data !== null && resp.code == 200) {
        // resp.data=false;
        if (!resp.data) {
          this.navCtrl.push('MystatePage', {'Id': this.videoID});
        } else {
          this.valite.showtoast("不可以重复评论哦^—^", this.toastCtrl, "middle");
          // this.toastCtrl.create({
          //   message:'您已经评论过了，不能重复评论哦',
          //   duration:2000,
          //   position:'middle'
          // }).present();
        }
      } else if (resp.data !== null && resp.code == 1401) {
        this.applicationService.freshTokenn();
      }
    }, error2 => {
      // console.log(error2);
    });
  }


  /**
   打开评论
   */
  open_mystate() {
    console.log("aaa");
    this.navCtrl.push('MystatePage');
  };

  doInfinite(infiniteScroll) {
    // console.log('Begin async operation');

    setTimeout(() => {
      this.loadmore();

      // console.log('Async operation has ended');
      infiniteScroll.complete();


    }, 1000);
  }

  loadmore() {




    if (this.lastPage) {
      if (this.scrollSign) {
        this.valite.showtoast("我也是有底线的！", this.toastCtrl, "bottom");
        // this.toastCtrl.create({
        //   message:'我也是有底线的',
        //   duration:2000,
        //   position:'bottom',
        //
        // }).present();
        this.scrollSign = false;
      }
      else {
        this.scrollSign = true
      }

    } else {
      ++this.currentPage;
      this.getVideoDetailservice.getVideoCommend(this.videoID, this.currentPage).subscribe(resp => {

        // console.log("aaaaaa")
        if (resp.data !== null) {

          // console.log(resp.data);
          console.log(resp.data);
          this.lastPage = resp.data.isLastPage;


          this.comment_list = this.comment_list.concat(resp.data.list);

          // this.sliders=resp.data;
          // console.log(this.video_datas);
          // console.log(this.video_datas[0].img);
          // console.log(this.video_datas.list[4].img);
        } else {
          console.log("resp.data==null")
        }
      }, error2 => {
        console.log("error");
        console.log(error2);
      });
    }

  }


setStar(){
 let  star = document.getElementById("star") ;

  var leftwidth = Math.floor(this.average_score/5*100);
  star.style.width = leftwidth.toString();
  alert(leftwidth);

}



}
